﻿using System.Drawing;
using System.Linq;
using RRRSRoguelike.Entities;
using RRRSRoguelike.Entities.Creatures;
using RRRSRoguelike.Managers;

namespace RRRSRoguelike.Helpers.Behaviors
{
	/// <summary>
	/// Describes the mindless behavior.
	/// </summary>
	public class Mindless
	{
		public static void MoveToTarget(Monster caller, Point target)
		{
			var tempPoint = caller.Position;
			var Monsters = GameManager.Instance.CreatureManager.Monsters;
			caller.Flags["hasMoved"] = false;

			//move on x axis toward player
			if (caller.X != target.X)
				tempPoint.X += (caller.X > target.X) ? -1 : 1;
			//move on y axis toward player
			if (caller.Y != target.Y)
				tempPoint.Y += (caller.Y > target.Y) ? -1 : 1;

			DungeonLevel.ClampToDungeon(tempPoint);

			// m stands for Monster in monsters. Prevents monsters from stacking(moving onto the same square).
			if (GameManager.Instance.DungeonLevel.IsOKToMove(tempPoint) &&
					!Monsters.Any(m => m.X == tempPoint.X && m.Y == tempPoint.Y))
			{
				caller.Flags["hasMoved"] = true;
				caller.Position = tempPoint;
			}
			else if (GameManager.Instance.DungeonLevel.IsOKToMove(new Point(tempPoint.X, caller.Position.Y)) &&
				!Monsters.Any(m => m.X == tempPoint.X && m.Y == caller.Position.Y))
			{
				//this resets the temp move to the orginal position resulting in no move on the y axis
				tempPoint.Y = caller.Position.Y;
				caller.Flags["hasMoved"] = true;
				caller.Position = tempPoint;
			}
			else if (GameManager.Instance.DungeonLevel.IsOKToMove(new Point(caller.Position.X, tempPoint.Y)) &&
					 !Monsters.Any(m => m.X == caller.Position.X && m.Y == tempPoint.Y))
			{
				//this resets the temp move to the orginal position resulting in no move on the x axis
				tempPoint.X = caller.Position.X;
				caller.Flags["hasMoved"] = true;
				caller.Position = tempPoint;
			}
			//if blocking monster won't move or temp is where we are standing then give up
			else if (Monsters.Where(m => m.Position == tempPoint).Count() > 0 &&
					Monsters.Where(m => m.Position == tempPoint).FirstOrDefault().Flags["hasMoved"])
				caller.Flags["hasMoved"] = true;

			else if (caller.X == tempPoint.X && caller.Y == tempPoint.Y)
				caller.Flags["hasMoved"] = true;

			else if (Monsters.Where(m => m.Position == tempPoint).Count() > 0 &&
					!Monsters.Where(m => m.Position == tempPoint).FirstOrDefault().Flags["hasMoved"])
			{
				caller.Flags["hasMoved"] = false;
			}
			else
				caller.Flags["hasMoved"] = true;
		}
	}
}
